﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SJ.Platform.Extend.Response;
using SJ.Platform.Middleware.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.Middleware.Middleware
{
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionHandlingMiddleware> _logger;

        public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An error occurred while processing a request.");
                // 处理异常
                await HandleExceptionAsync(context, ex);
            }
        }

        public async Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            var statusCode = StatusCodes.Status500InternalServerError; // 默认状态码为500  
            
            // 对于API请求，返回JSON响应  
            context.Response.ContentType = context.Request.ContentType;
            context.Response.StatusCode = statusCode;

            await context.Response.WriteAsJsonAsync(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "An error occurred while processing your request." + ex.Message, false)); // 需要安装Microsoft.AspNetCore.Mvc.NewtonsoftJson或System.Text.Json.Http 
        }
    }
}
